package com.gjy.util;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-31 13:52:03
 */
public class DatetimeUtil {

    public static String parse(long millis) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(millis));
    }

    /**
     * 获取提供时间月份的第一天
     */
    public static <T> T firstDayOfMonth(T t) {
        TemporalAdjuster adjuster = TemporalAdjusters.firstDayOfMonth();

        if (t instanceof LocalDate) {
            LocalDate l = (LocalDate) t;
            return (T) l.with(adjuster);
        } else if (t instanceof LocalDateTime) {
            LocalDateTime l = (LocalDateTime) t;
            return (T) l.with(adjuster);
        } else if (t instanceof Instant) {
            Instant l = (Instant) t;
            return (T) l.with(adjuster);
        } else {
            return t;
        }
    }

    /**
     * 获取提供时间月份的最后一天
     */
    public static <T> T lastDayOfMonth(T t) {
        TemporalAdjuster adjuster = TemporalAdjusters.lastDayOfMonth();

        if (t instanceof LocalDate) {
            LocalDate l = (LocalDate) t;
            return (T) l.with(adjuster);
        } else if (t instanceof LocalDateTime) {
            LocalDateTime l = (LocalDateTime) t;
            return (T) l.with(adjuster);
        } else if (t instanceof Instant) {
            Instant l = (Instant) t;
            return (T) l.with(adjuster);
        } else {
            return t;
        }
    }
}
